package com.greensam.common.exception;

import com.greensam.common.constant.SystemConstant;
import com.greensam.common.mq.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.text.MessageFormat;

/**
 * 全局异常处理器
 *
 * @Author: Machengrui
 * @Date: 2025/2/8 14:59
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(GreensamApiException.class)
    public CommonResult<?> handleGreensamApiException(GreensamApiException e) {
        String message = e.getMessage();
        if (e.getParams() != null && e.getParams().length > 0) {
            message = MessageFormat.format(message, e.getParams());
        }
        log.error(message, e);
        return CommonResult.failed(e.getCode(), message);
    }

    /**
     * 处理SQL语法解析异常
     */
    @ExceptionHandler(BadSqlGrammarException.class)
    public CommonResult<?> handleBadSqlGrammarException(BadSqlGrammarException e) {
        String message = e.getMessage();
        log.error(message, e);
        return CommonResult.failed(SystemConstant.ErrorMessage.ERROR_SQL_SYNTAX);
    }

    /**
     * 处理SQL语法解析异常
     */
    @ExceptionHandler(SQLException.class)
    public CommonResult<?> handleChubException(SQLException e) {
        String message = e.getMessage();
        log.error(message, e);
        return CommonResult.failed(SystemConstant.ErrorMessage.ERROR_SQL_SYNTAX);
    }

    /**
     * 处理全局异常
     */
    @ExceptionHandler(Throwable.class)
    public CommonResult<?> handleException(Throwable e) {
        String message = e.getMessage();
        log.error(message, e);
        return CommonResult.failed(e.getMessage());
    }
}
